<template>
  <div class="todo-container">
    <div class="todo-wrap">
      <Header :addTodo="addTodo" />
      <List :todos="todos" :updateTodo="updateTodo" :delTodo="delTodo" />
      <!-- 
        表达式比较简单直接写，
        表达式比较长，比较复杂，建议定义在计算属性中使用 
      -->
      <Footer
        :total="todos.length"
        :isDoneCount="isDoneCount"
        :updateAllTodosIsDone="updateAllTodosIsDone"
        :delIsDoneTodos="delIsDoneTodos"
      />
    </div>
  </div>
</template>

<script>
import Header from "./views/Header";
import List from "./views/List";
import Footer from "./views/Footer";

export default {
  name: "App",
  data() {
    return {
      todos: [
        { id: 1, name: "吃饭", isDone: false },
        { id: 2, name: "睡觉", isDone: true },
        { id: 3, name: "敲代码", isDone: false },
        { id: 4, name: "打游戏", isDone: false },
      ],
    };
  },
  methods: {
    // 添加todo
    addTodo(name) {
      this.todos.unshift({
        id: Date.now(),
        name,
        isDone: false,
      });
    },
    // 更新isDone
    updateTodo(id) {
      // 如果都返回false，没有找到，最终返回值是undefined
      // 如果有一个返回true，就找到了，中止遍历，最终返回值是当前遍历这项元素
      const todo = this.todos.find((todo) => todo.id === id);
      todo.isDone = !todo.isDone;
    },
    // 删除todo
    delTodo(id) {
      this.todos = this.todos.filter((todo) => todo.id !== id);
    },
    // 全选/全不选
    updateAllTodosIsDone(isAllChecked) {
      this.todos.forEach((todo) => (todo.isDone = isAllChecked));
    },
    // 批量删除
    delIsDoneTodos() {
      this.todos = this.todos.filter((todo) => !todo.isDone);
    },
  },
  computed: {
    // 已完成数量
    isDoneCount() {
      return this.todos.reduce((p, c) => {
        return p + (c.isDone ? 1 : 0);
      }, 0);
    },
  },
  components: {
    Header,
    List,
    Footer,
  },
};
</script>

<style>
/*app*/
.todo-container {
  width: 600px;
  margin: 0 auto;
}
.todo-container .todo-wrap {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
}
</style>